import { loginAPI, LoginFormType, sendCodeAPI } from '@/api/login';
import { getUserInfoAPI, getUserProfileAPI, updatePhotoAPI, updateProfileAPI } from '@/api/user';
import { setAuth } from '@/utils/storage';
import { AppDispatch } from '..';
import { ProfileType } from '../reducer/user';

export const sendCodeAction = (mobile: string) => {
  return async () => {
    await sendCodeAPI(mobile);
  };
};

export const loginAction = (data: LoginFormType) => {
  return async (dispatch: AppDispatch) => {
    const res = await loginAPI(data);
    setAuth(res.data);

    dispatch({
      type: 'user/saveAuth',
      payload: res.data,
    });
  };
};

export const getUserInfoAction = () => {
  return async (dispacth: AppDispatch) => {
    const res = await getUserInfoAPI();
    dispacth({
      type: 'user/saveUserInfo',
      payload: res.data,
    });
  };
};
export const getUserprofileAction = () => {
  return async (dispacth: AppDispatch) => {
    const res = await getUserProfileAPI();
    dispacth({
      type: 'user/saveProfile',
      payload: res.data,
    });
  };
};

export const updatePhotoAction = (data: FormData) => {
  return async (dispacth: AppDispatch) => {
    const res = await updatePhotoAPI(data);
    dispacth({
      type: 'user/updateProfile',
      payload: res.data,
    });
  };
};

export const updateProfileAction = (data: Partial<ProfileType>) => {
  return async (dispacth: AppDispatch) => {
    await updateProfileAPI(data);
    dispacth({
      type: 'user/updateProfile',
      payload: data,
    });
  };
};
